package org.csu.code.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhenzi.sms.ZhenziSmsClient;
import org.csu.code.api.common.CommonResponse;
import org.csu.code.api.entity.Account;
import org.csu.code.api.persistence.AccountMapper;
import org.csu.code.api.service.AccountService;
import org.csu.code.api.service.RedisService;
import org.csu.code.api.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/code/")
public class CodeController {
    private static final String apiUrl = "https://sms_developer.zhenzikj.com";
    private static final String appId = "108562";
    private static final String appSecret = "3a94820d-5274-49c5-95a9-326bd8f4bb5f";
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AccountService accountService;
    @Autowired
    private RedisService redisService;

    @GetMapping("getcode/{phoneNum}")
    @ResponseBody
    public CommonResponse<String> send(@PathVariable("phoneNum") String phoneNum, HttpSession httpSession){
        try {
            JSONObject json = null;
            //随机生成验证码
            String code = String.valueOf(new Random().nextInt(999999));
            //将验证码通过榛子云接口发送至手机
            ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("number", phoneNum);
            params.put("templateId", "4420");
            String[] templateParams = new String[2];
            templateParams[0] = code;
            templateParams[1] = "1";
            params.put("templateParams", templateParams);
            String result = client.send(params);

            json = JSONObject.parseObject(result);
            if (json.getIntValue("code")!=0){//发送短信失败
                return  CommonResponse.createForError("发送失败");
            }
            //将验证码存到session中,同时存入创建时间
            //以json存放，这里使用的是阿里的fastjson
            json = new JSONObject();
            json.put("memPhone",phoneNum);
            json.put("code",code);
            json.put("createTime",System.currentTimeMillis());
            // 将认证码存入SESSION
//            httpSession.setAttribute("code",json);
            // 生产验证码字符串并保存到 Redis 中，ip-rightCode，有效期为 1 小时
            String token1 = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token1, json.toJSONString(), 1, TimeUnit.HOURS);
            return CommonResponse.createForSuccess("发送成功",token1);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.createForError("发送失败");
        }
    }

    @GetMapping("codelogin/{code}")
    @ResponseBody
    public CommonResponse<AccountVO> codeLogin(@PathVariable("code") String code, HttpServletRequest httpServletRequest) {
        String token1 = httpServletRequest.getHeader("token");
        // 从 Redis 中校验
        JSONObject json = JSONObject.parseObject(redisTemplate.opsForValue().get(token1));
        String TrueCode = json.getString("code");
        String tell = json.getString("memPhone");
        if (code.equals(TrueCode)) {
            Account account = accountMapper.selectOne(Wrappers.<Account>query().eq("phone",tell));
            if (account != null) {
                AccountVO accountVO = accountService.accountToAccountVO(account);
                String token = UUID.randomUUID().toString();
                redisService.set(token, account.getUserid()+"");
                return CommonResponse.createForLogin("登录成功",token,accountVO);
            } else {
                return CommonResponse.createForError("此手机号尚未注册，请先注册");
            }
        } else {
            return CommonResponse.createForError("验证码错误");
        }
    }
}
